package com.leyou.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.zaxxer.hikari.HikariDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class DataSourceProxyConfig {

//    @Bean
//    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
//        // 订单服务中引入了mybatis-plus，所以要使用特殊的SqlSessionFactoryBean
//        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
//        // 代理数据源
//        sqlSessionFactoryBean.setDataSource(new DataSourceProxy(dataSource));
//        // 生成SqlSessionFactory
//        return sqlSessionFactoryBean.getObject();

//    }
    /*
    利用seata中的DataSourceProxy类对原始的连接池做了代理，
    以后执行业务sql时，就会被seata给拦截，并且分析语义，生成beforeImage和afterImage。
     */
@Bean
public DataSource dataSource(DataSourceProperties properties){
    // 创建连接池
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setDriverClassName(properties.getDriverClassName());
    dataSource.setJdbcUrl(properties.getUrl());
    dataSource.setUsername(properties.getUsername());
    dataSource.setPassword(properties.getPassword());
    // 对连接池做代理
    return new DataSourceProxy(dataSource);
}
}